import React, {useCallback, useState} from "react"
import {Scan} from "@nutui/icons-react-taro";
import {Button, ButtonProps} from "@nutui/nutui-react-taro";
import Taro from "@tarojs/taro";
import {isGoodsBarcodeExists} from "../apis/GoodsApi";
import {barcodeNotExisted} from "../utils/ScanCodeUtils";
export interface ScanBarcodeButtonProps extends Omit<Partial<ButtonProps>, "ref"> {
    onScanSuccess: (barcode: string, continueScan:()=>Promise<void>) => Promise<void>
    text?:React.ReactNode|null
}

const ScanBarcodeButton: React.FC<ScanBarcodeButtonProps> = (props) => {
    const [loading, setLoading] = useState(false)
    let onClick = useCallback(async () => {
        try {
            setLoading(true)
            let result = await Taro.scanCode({
                scanType: ["barCode"],
            });
            let barcode = result.result
            let exists = (await isGoodsBarcodeExists(barcode)).data;
            if (!exists) {
                await barcodeNotExisted(barcode)

                await onClick()
                return
            }
            await props.onScanSuccess(barcode,onClick)
        } finally {
            setLoading(false)
        }
    1},[props.onScanSuccess])
    return <>
        <Button {...props} icon={<Scan/>} type={"primary"} loading={loading} onClick={onClick}>{props.children??"扫码"}</Button>
    </>
}

export default ScanBarcodeButton
